/* 
 * File:   Handle.h
 * Author: root
 *
 * Created on 8 listopad 2011, 09:22
 */

#ifndef HANDLE_H
#define	HANDLE_H

#include <boost/assert.hpp>

#include <vector>

template<typename _Data, size_t _CorrectionBits=16>
class Handle
{
private:

     enum
        {
            MAX_BITS_MAGIC=_CorrectionBits,
            MAX_BITS_INDEX=32-MAX_BITS_MAGIC,
            MAX_MAGIC=(1<<MAX_BITS_MAGIC)-1,
            MAX_INDEX=(1<<MAX_BITS_INDEX)-1,
        };
    union
    {
       

        struct
        {
            unsigned int magic:MAX_BITS_MAGIC;
            unsigned int index:MAX_BITS_INDEX;
        };

        unsigned int handle;

    };

public:

    Handle()
    : handle(0)
    {
    }

    void init(unsigned int newIndex)
    {
        BOOST_ASSERT_MSG(newIndex<=MAX_INDEX,"invalid index range");
        BOOST_ASSERT_MSG(isNull(),"invoked init(unsigned int newIndex) for non null handle");

        static unsigned int newMagic=0;
        newMagic++;
        if(newMagic>MAX_MAGIC)newMagic=1;

        index=newIndex;
        magic=newMagic;
    }

    unsigned int getMagic() const{return magic;}
    unsigned int getIndex() const{return index;}
    unsigned int getHandle() const{return handle;}
    bool isNull()const{return handle==0;}
    operator unsigned int () const{return handle;}
};

#endif	/* HANDLE_H */

